
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class clientF implements Runnable {

    // Declaration section
    // clientClient: the client socket
    // os: the output stream
    // is: the input stream
    static Socket clientSocket = null;

    static String aenviar = null;
    static String[] ordenCompleta = null;
    
    static String ruta = "/";
    static BufferedReader inputLine = null;
    static boolean closed = false;

    public static void main(String[] args) {
        PrintStream os = null;
        DataInputStream is = null;
        // The default port    

        int port_number = 2222;
        String host = "localhost";
//        String host = "localhost";
        // Initialization section:
        // Try to open a socket on a given host and port
        // Try to open input and output streams
        try {
            clientSocket = new Socket(host, port_number);
            inputLine = new BufferedReader(new InputStreamReader(System.in));

            os = new PrintStream(clientSocket.getOutputStream());
            is = new DataInputStream(clientSocket.getInputStream());
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + host);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to the host " + host);
        }

        // If everything has been initialized then we want to write some data
        // to the socket we have opened a connection to on port port_number 

        if (clientSocket != null && os != null && is != null) {
            try {
                new Thread(new clientF()).start();
                while (!closed) {
                    aenviar = inputLine.readLine();
                    ordenCompleta = aenviar.split(" ");
                    if(ordenCompleta[0].equals("cpL2R")){
                        //Mandamos el nombre del archivo
                        os.println(aenviar);
                        mandar(os, ordenCompleta[1]);
                        os.println("ruta " + "LOCAL: " + ruta + "> ");
                    }
                    else if(ordenCompleta[0].equals("cpR2L")){
                        //Mandamos el nombre del archivo
                        os.println(aenviar);
                        byte[] arr = new byte[32*1024];
                        is.readFully(arr);
                        if(arr != null && arr.length > 0){
                            OutputStream out = new FileOutputStream(ordenCompleta[2] + "/" + ordenCompleta[1]);
                            InputStream in = new ByteArrayInputStream(arr);
                            int len;
                            while ((len = in.read(arr)) > 0) {
                                out.write(arr, 0, len);
                            }
                            in.close();
                            out.close();
                        }               
                        os.println("ruta " + "LOCAL: " + ruta + "> ");
                    }
                    else if (ordenCompleta[0].equals("dirL")) {
                        try {
                            File directorio = new File(ruta);
                            File[] archivos = directorio.listFiles();
                            for (int i = 0; i < archivos.length; i++) {
                                System.out.println(archivos[i].toString());
                            }
                        } catch (Exception ex) {
                            System.out.println("La ruta especificada no existe");
                        }
                        os.println("ruta " + "LOCAL: " + ruta + "> ");
                    } else if (ordenCompleta[0].equals("ipL")) {
                        try {
                            InetAddress localhost = InetAddress.getLocalHost();
                            InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
                            if (allMyIps != null && allMyIps.length >= 1) {
                                for (int i = 0; i < allMyIps.length; i++) {
                                    System.out.println(" " + allMyIps[i]);
                                }
                            }
                        } catch (UnknownHostException e) {
                            System.out.println("(error retrieving server host name)");
                        }
                        os.println("ruta " + "LOCAL: " + ruta + "> ");
                    } else if (ordenCompleta[0].equals("rmL")) {
                        try {

                            File Aborrar = new File("/" + ruta + "/" + ordenCompleta[1]);

                            System.out.println("/" + ruta + "/" + ordenCompleta[1]);

                            boolean success = Aborrar.delete();
                            if (!success) {
                                System.out.println("No se puede borrar");
                            }
                            if (success) {
                                System.out.println("Archivo borrado");
                            }
                        } catch (Exception ex) {
                            System.out.println("La ruta especificada no existe");
                        }
                        os.println("ruta " + "LOCAL: " + ruta + "> ");
                    } else if (ordenCompleta[0].equals("cdL")) {
                        if (ordenCompleta.length > 1) {
                            if (ordenCompleta[1].equals("..")) {
                                if (!ruta.equals("")) {
                                    ruta = ruta.substring(0, ruta.lastIndexOf("/"));
                                    if (ruta.equals("")) {
                                        ruta = "/";
                                    }
                                }
                            } else {
                                if (new File(ruta + ordenCompleta[1]).isDirectory()) {
                                    ruta += ordenCompleta[1];
                                } else if (new File(ruta + "/" + ordenCompleta[1]).isDirectory()) {
                                    ruta += "/" + ordenCompleta[1];
                                } else {
                                    System.out.println("La ruta especificada no existe");
                                }
                            }
                        }
                        os.println("ruta " + "LOCAL: " + ruta + "> ");
                    } else if (ordenCompleta[0].equals("cpL")) {
                        if (ordenCompleta.length == 3) {
                            File archivoACopiar;
                            OutputStream out;
                            //Buscamos en el camino que fue proporcionado
                            if (new File(ordenCompleta[2]).isDirectory()) {
                                if (new File(ordenCompleta[1]).isFile()) {
                                    archivoACopiar = new File(ordenCompleta[1]);
                                    try (InputStream in = new FileInputStream(archivoACopiar)) {
                                        try {
                                            out = new FileOutputStream(ordenCompleta[2] + "/" + archivoACopiar.getName());
                                            byte[] buf = new byte[1024];
                                            int len;
                                            while ((len = in.read(buf)) > 0) {
                                                out.write(buf, 0, len);
                                            }
                                            in.close();
                                            out.close();
                                        } catch (Exception ex) {
                                            System.out.println(ex.getMessage());
                                        }
                                    } catch (Exception ex) {
                                        System.out.println(ex.getMessage());
                                    }
                                } //Buscamos en root
                                else if (new File(ruta + ordenCompleta[1]).isFile()) {
                                    archivoACopiar = new File("/" + ordenCompleta[1]);
                                    try (InputStream in = new FileInputStream(archivoACopiar)) {
                                        try {
                                            out = new FileOutputStream(ordenCompleta[2] + "/" + archivoACopiar.getName());
                                            byte[] buf = new byte[1024];
                                            int len;
                                            while ((len = in.read(buf)) > 0) {
                                                out.write(buf, 0, len);
                                            }
                                            in.close();
                                            out.close();
                                        } catch (Exception ex) {
                                            System.out.println(ex.getMessage());
                                        }
                                    }
                                } //Buscamos en el directorio en el que estamos
                                else if (new File(ruta + "/" + ordenCompleta[1]).isFile()) {
                                    archivoACopiar = new File(ruta + "/" + ordenCompleta[1]);
                                    try (InputStream in = new FileInputStream(archivoACopiar)) {
                                        try {
                                            out = new FileOutputStream(ordenCompleta[2] + "/" + archivoACopiar.getName());
                                            byte[] buf = new byte[1024];
                                            int len;
                                            while ((len = in.read(buf)) > 0) {
                                                out.write(buf, 0, len);
                                            }
                                            in.close();
                                            out.close();
                                        } catch (Exception ex) {
                                            System.out.println(ex.getMessage());
                                        }
                                    }
                                } else {
                                    System.out.println("El archivo no existe o escribio la ruta de manera incorrecta");
                                }
                            } else {
                                System.out.println("El directorio destino no existe o escribio la ruta de manera incorrecta");
                            }
                        } else {
                            System.out.println("Comando incorrecto");
                        }
                        os.println("ruta " + "LOCAL: " + ruta + "> ");
                    }  else {
                        os.println(aenviar);
                        if (!ordenCompleta[0].equals("log")) {
                            os.println("ruta " + "LOCAL: " + ruta + "> ");
                        }
                    }
                }
                os.close();
                is.close();
                clientSocket.close();
            } catch (IOException e) {
                System.err.println("IOException:  " + e);
            }
        }

    }

    public static void mandar(PrintStream os, String archivo) throws IOException {
        File archivoACopiar = new File((ruta.equals("/")? "":ruta) + "/" + archivo);
        if(archivoACopiar.exists()){
            InputStream in = null;
            try {
                in = new FileInputStream(archivoACopiar);
                try {
                    byte[] buf = new byte[32*1024];
                    int len;
                    while ((len = in.read(buf, 0, buf.length)) > 0);
                    os.write(buf);
                    in.close();
                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                }
            }
            catch (Exception ex) {
                System.out.println(ex.getMessage());
                if(in != null)
                    in.close();
            }
        }
        else{
            System.out.println("El archivo no existe");
        }
    }
    
    public static void recibir(){
        
    }

    public void run() {
        DataInputStream is = null;
        try {
            String responseLine;
            is = new DataInputStream(clientSocket.getInputStream());
            // Keep on reading from the socket till we receive the "Bye" from the server,
            // once we received that then we want to break.
            try {
                while ((responseLine = is.readLine()) != null) {
                    int i = 0;
    //                if (!responseLine.contains("ok")) {
                        System.out.println(responseLine);
    //                } else {
    //                    mandar(responseLine.split(" ")[1]);
    //                }
                    if (responseLine.indexOf("*** Bye") != -1) {
                        break;
                    }
                }
                closed = true;
            } catch (IOException e) {
                System.err.println("IOException:  " + e);
            }
        } catch (IOException ex) {
            Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                is.close();
            } catch (IOException ex) {
                Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}